import React, { useState, useEffect } from 'react'
import { Card, Table, Button, Modal, Form, Input, Select, Tag, Space, message, Row, Col, Statistic, Alert } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, PoweroffOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons'
import MainLayout from '../components/layout/MainLayout'
import { deviceAPI } from '../utils/api'

const { Option } = Select

interface Device {
  _id: string
  name: string
  type: string
  location: string
  status: 'online' | 'offline' | 'error' | 'maintenance'
  ip: string
  specifications?: {
    model?: string
    manufacturer?: string
    installDate?: string
  }
}

interface DeviceStats {
  total: number
  online: number
  offline: number
  warning: number
  maintenance: number
  onlineRate: string
}

export default function Devices() {
  const [devices, setDevices] = useState<Device[]>([])
  const [loading, setLoading] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  const [editingDevice, setEditingDevice] = useState<Device | null>(null)
  const [form] = Form.useForm()
  const [error, setError] = useState<string | null>(null)
  const [stats, setStats] = useState<DeviceStats>({
    total: 0,
    online: 0,
    offline: 0,
    warning: 0,
    maintenance: 0,
    onlineRate: '0'
  })

  const fetchDevices = async () => {
    setLoading(true)
    setError(null)
    try {
      console.log('正在获取设备列表...')
      const response = await deviceAPI.getList()
      console.log('设备列表响应:', response.data)
      
      if (response.data.success) {
        setDevices(response.data.data || [])
        console.log(response.data.data);
        
      } else {
        setError('获取设备列表失败: ' + (response.data.error || '未知错误'))
      }
    } catch (error: any) {
      console.error('获取设备列表错误:', error)
      if (error.code === 'ECONNREFUSED' || error.message.includes('Network Error')) {
        setError('无法连接到后端服务，请确保后端服务正在运行')
      } else {
        setError('获取设备列表失败: ' + (error.response?.data?.error || error.message))
      }
    } finally {
      setLoading(false)
    }
  }

  const fetchStats = async () => {
    try {
      console.log('正在获取设备统计...')
      const response = await deviceAPI.getStats()
      console.log('设备统计响应:', response.data)
      
      if (response.data.success) {
        setStats(response.data.data)
      }
    } catch (error: any) {
      console.error('获取设备统计错误:', error)
      // 统计数据获取失败不显示错误，使用默认值
    }
  }

  useEffect(() => {
    fetchDevices()
    fetchStats()
  }, [])

  const columns = [
    {
      title: '设备名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: Device) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>
            {record.specifications?.model || '未知型号'}
          </div>
        </div>
      )
    },
    {
      title: '设备类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const typeMap: { [key: string]: { color: string, text: string } } = {
          camera: { color: 'blue', text: '监控摄像头' },
          sensor: { color: 'green', text: '传感器' },
          access_control: { color: 'orange', text: '门禁控制' },
          alarm: { color: 'red', text: '报警器' },
          lighting: { color: 'cyan', text: '照明控制' },
          hvac: { color: 'purple', text: '空调控制' }
        }
        const config = typeMap[type] || { color: 'default', text: type }
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          online: { color: 'green', text: '在线' },
          offline: { color: 'red', text: '离线' },
          error: { color: 'orange', text: '故障' },
          maintenance: { color: 'gray', text: '维护中' }
        }
        const config = statusMap[status as keyof typeof statusMap] || { color: 'default', text: status }
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: 'IP地址',
      dataIndex: 'ip',
      key: 'ip'
    },
    {
      title: '制造商',
      key: 'manufacturer',
      render: (record: Device) => record.specifications?.manufacturer || '未知'
    },
    {
      title: '安装日期',
      key: 'installDate',
      render: (record: Device) => {
        const date = record.specifications?.installDate
        return date ? new Date(date).toLocaleDateString() : '未知'
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Device) => (
        <Space>
          <Button 
            type="link" 
            icon={<PoweroffOutlined />}
            onClick={() => handleToggleDevice(record)}
            style={{ color: record.status === 'online' ? '#ff4d4f' : '#52c41a' }}
          >
            {record.status === 'online' ? '关闭' : '启动'}
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record._id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ]

  const handleAdd = () => {
    setEditingDevice(null)
    form.resetFields()
    setModalVisible(true)
  }

  const handleEdit = (device: Device) => {
    setEditingDevice(device)
    form.setFieldsValue({
      name: device.name,
      type: device.type,
      location: device.location,
      ip: device.ip,
      model: device.specifications?.model,
      manufacturer: device.specifications?.manufacturer,
      installDate: device.specifications?.installDate
    })
    setModalVisible(true)
  }

  const handleDelete = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个设备吗？',
      onOk: async () => {
        try {
          const response = await deviceAPI.delete(id)
          if (response.data.success) {
            message.success('删除成功')
            fetchDevices()
            fetchStats()
          } else {
            message.error(response.data.error || '删除失败')
          }
        } catch (error: any) {
          message.error(error.response?.data?.error || '删除失败')
        }
      }
    })
  }

  const handleToggleDevice = async (device: Device) => {
    try {
      const action = device.status === 'online' ? 'shutdown' : 'startup'
      const response = await deviceAPI.control(device._id, action)
      
      if (response.data.success) {
        message.success(response.data.message)
        fetchDevices()
        fetchStats()
      } else {
        message.error(response.data.error || '操作失败')
      }
    } catch (error: any) {
      message.error(error.response?.data?.error || '操作失败')
    }
  }

  const handleSave = async () => {
    try {
      const values = await form.validateFields()
      setLoading(true)
      
      // 构造设备数据
      const deviceData = {
        name: values.name,
        type: values.type,
        location: values.location,
        ip: values.ip,
        specifications: {
          model: values.model,
          manufacturer: values.manufacturer,
          installDate: values.installDate
        }
      }
      
      let response
      if (editingDevice) {
        response = await deviceAPI.update(editingDevice._id, deviceData)
      } else {
        response = await deviceAPI.create(deviceData)
      }
      
      if (response.data.success) {
        message.success(response.data.message)
        setModalVisible(false)
        form.resetFields()
        setEditingDevice(null)
        fetchDevices()
        fetchStats()
      } else {
        message.error(response.data.error || '操作失败')
      }
    } catch (error: any) {
      if (error.response?.data?.error) {
        message.error(error.response.data.error)
      } else if (error.errorFields) {
        message.error('请检查表单输入')
      } else {
        message.error('操作失败: ' + error.message)
      }
    } finally {
      setLoading(false)
    }
  }

  return (
    <MainLayout>
      {error && (
        <Alert
          message="连接错误"
          description={error}
          type="error"
          showIcon
          closable
          onClose={() => setError(null)}
          style={{ marginBottom: 16 }}
          action={
            <Button size="small" onClick={() => {
              setError(null)
              fetchDevices()
              fetchStats()
            }}>
              重试
            </Button>
          }
        />
      )}

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic title="设备总数" value={stats.total} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="在线设备" 
              value={stats.online} 
              valueStyle={{ color: '#3f8600' }}
              suffix={`/ ${stats.total}`}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="离线设备" 
              value={stats.offline} 
              valueStyle={{ color: '#cf1322' }}
              suffix={`/ ${stats.total}`}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="在线率" 
              value={stats.onlineRate} 
              valueStyle={{ color: '#1890ff' }}
              suffix="%"
            />
          </Card>
        </Col>
      </Row>

      <Card 
        title="设备管理" 
        extra={
          <Space>
            <Button 
              icon={<ReloadOutlined />}
              onClick={() => {
                fetchDevices()
                fetchStats()
              }}
              loading={loading}
            >
              刷新
            </Button>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              添加设备
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={devices}
          rowKey="_id"
          loading={loading}
          pagination={{ 
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
          }}
        />
      </Card>

      {/* 设备编辑/新增模态框 */}
      <Modal
        title={editingDevice ? '编辑设备' : '添加设备'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => {
          setModalVisible(false)
          form.resetFields()
          setEditingDevice(null)
        }}
        width={600}
        confirmLoading={loading}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            status: 'offline'
          }}
        >
          <Form.Item
            name="name"
            label="设备名称"
            rules={[{ required: true, message: '请输入设备名称' }]}
          >
            <Input placeholder="请输入设备名称" />
          </Form.Item>
          
          <Form.Item
            name="type"
            label="设备类型"
            rules={[{ required: true, message: '请选择设备类型' }]}
          >
            <Select placeholder="请选择设备类型">
              <Option value="camera">监控摄像头</Option>
              <Option value="sensor">传感器</Option>
              <Option value="access_control">门禁控制</Option>
              <Option value="alarm">报警器</Option>
              <Option value="lighting">照明控制</Option>
              <Option value="hvac">空调控制</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="location"
            label="安装位置"
            rules={[{ required: true, message: '请输入安装位置' }]}
          >
            <Input placeholder="请输入安装位置" />
          </Form.Item>
          
          <Form.Item
            name="ip"
            label="IP地址"
            rules={[
              { required: true, message: '请输入IP地址' },
              { pattern: /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/, message: '请输入正确的IP地址' }
            ]}
          >
            <Input placeholder="请输入IP地址" />
          </Form.Item>
          
          <Form.Item
            name="model"
            label="设备型号"
          >
            <Input placeholder="请输入设备型号" />
          </Form.Item>
          
          <Form.Item
            name="manufacturer"
            label="制造商"
          >
            <Input placeholder="请输入制造商" />
          </Form.Item>
          
          <Form.Item
            name="installDate"
            label="安装日期"
          >
            <Input type="date" />
          </Form.Item>
        </Form>
      </Modal>
    </MainLayout>
  )
}
